package com.cloudeasy.file.controller;

import com.cloudeasy.file.properties.FileProperties;
import com.cloudeasy.file.util.FileUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@Controller
@CrossOrigin
public class FileController {

    private final FileProperties fileProperties;

    public FileController(FileProperties fileProperties) {
        this.fileProperties = fileProperties;
    }

    /**
     * 上传文件
     *
     * @param file {@link MultipartFile}
     * @return 保存文件名
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        return FileUtil.save(file, fileProperties.getPath());
    }

    /**
     * 获取文件
     *
     * @param fileName 文件名
     * @param response {@link HttpServletResponse}
     */
    @GetMapping("/{fileName}")
    public void get(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        FileUtil.get(fileProperties.getPath() + "/" + fileName, response);
    }
}
